import React, { useCallback, useEffect, useRef, useState } from 'react';
import styles from './Resizer.module.css';

export interface ResizerProps {
  direction: 'horizontal' | 'vertical';
  onResize: (delta: number) => void;
  className?: string;
}

// 垂直方向的grip-dots图标SVG组件
const GripDotsVertical = () => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width="10" 
    height="16" 
    viewBox="0 0 10 16" 
    className={styles.gripIcon}
  >
    <circle cx="2" cy="2" r="1.5" />
    <circle cx="8" cy="2" r="1.5" />
    <circle cx="2" cy="8" r="1.5" />
    <circle cx="8" cy="8" r="1.5" />
    <circle cx="2" cy="14" r="1.5" />
    <circle cx="8" cy="14" r="1.5" />
  </svg>
);

// 水平方向的grip-dots图标SVG组件
const GripDotsHorizontal = () => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width="16" 
    height="10" 
    viewBox="0 0 16 10" 
    className={styles.gripIcon}
  >
    <circle cx="2" cy="2" r="1.5" />
    <circle cx="8" cy="2" r="1.5" />
    <circle cx="14" cy="2" r="1.5" />
    <circle cx="2" cy="8" r="1.5" />
    <circle cx="8" cy="8" r="1.5" />
    <circle cx="14" cy="8" r="1.5" />
  </svg>
);

const Resizer: React.FC<ResizerProps> = ({ direction, onResize, className = '' }) => {
  const [isDragging, setIsDragging] = useState(false);
  const startPosRef = useRef(0);

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    e.preventDefault();
    setIsDragging(true);
    startPosRef.current = direction === 'horizontal' ? e.clientY : e.clientX;
    document.body.style.userSelect = 'none';
    document.body.style.cursor = direction === 'horizontal' ? 'row-resize' : 'col-resize';
  }, [direction]);

  const handleMouseMove = useCallback((e: MouseEvent) => {
    if (!isDragging) return;
    
    const currentPos = direction === 'horizontal' ? e.clientY : e.clientX;
    const delta = currentPos - startPosRef.current;
    onResize(delta);
    startPosRef.current = currentPos;
  }, [isDragging, direction, onResize]);

  const handleMouseUp = useCallback(() => {
    if (!isDragging) return;
    
    setIsDragging(false);
    document.body.style.userSelect = '';
    document.body.style.cursor = '';
  }, [isDragging]);

  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }
    
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, handleMouseMove, handleMouseUp]);

  useEffect(() => {
    return () => {
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
    };
  }, []);

  return (
    <div
      className={`${styles.resizer} ${styles[direction]} ${className} ${isDragging ? styles.dragging : ''}`}
      onMouseDown={handleMouseDown}
    >
      {direction === 'vertical' ? <GripDotsVertical /> : <GripDotsHorizontal />}
    </div>
  );
};

export default Resizer; 